<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <div><a href="#/one">1</a></div>
    <div><a href="#/two">2</a></div>
    <div id="text">欢迎</div>
</div>

<script>
    class Router {
        constructor() {
            this.routes = {}
            this.path = ''
        }
        //? 事件监听
        init() {
            window.addEventListener('load',this.refresh.bind(this))
            window.addEventListener('hashchange',this.refresh.bind(this))
        }
        //? 添加路径及其对应的hash变化回调函数
        route(path,callback) {
            this.routes[path] = callback || function () {}
        }
        //? 通过hash变化找到对应的回调函数执行
        refresh() {
            this.path  = location.hash.slice(1) || '/'
            this.routes[this.path]()
        }
    }
    const router = new Router()
    router.init()
    router.route('/one',function () {
        document.getElementById('text').innerText = 'one'
    })
    router.route('/two',function () {
        document.getElementById('text').innerText = 'two'
    })
</script>
</body>
</html>
